<template>
  <el-card>
    <!-- 查询 -->
    <el-form :model="queryParams" inline label-width="80px" class="search-form">
      <el-form-item label="设备名">
        <el-select v-model="queryParams.equipName" clearable placeholder="请选择设备" style="width: 150px">
          <el-option label="全部" value=""/>
          <el-option v-for="v in allNameOpts" :key="v" :label="v" :value="v"/>
        </el-select>
      </el-form-item>

      <!-- 科室下拉：改为独立接口 roomList() -->
      <el-form-item label="科室">
        <el-select v-model="queryParams.roomName" clearable placeholder="请选择科室" style="width: 150px">
          <el-option label="全部" value=""/>
          <el-option v-for="item in roomListOpts" :key="item.id" :label="item.roomName" :value="item.roomName"/>
        </el-select>
      </el-form-item>

      <el-form-item label="状态">
        <el-select v-model="queryParams.status" clearable placeholder="请选择状态" style="width: 150px">
          <el-option label="全部" value=""/>
          <el-option :value="1" label="正常"/>
          <el-option :value="0" label="报废"/>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="success" @click="handleAdd">新增设备</el-button>
      </el-form-item>
    </el-form>

    <!-- 维护提醒横幅 -->
    <el-alert
        v-if="maintenanceCount > 0"
        :title="`有 ${maintenanceCount} 台设备需要维护`"
        type="warning"
        :closable="false"
        show-icon
        style="margin-bottom: 12px;"
    />

    <!-- 表格 -->
    <el-table :data="tableData" border stripe style="width: 100%; margin:12px 0">
      <el-table-column prop="id" label="ID" width="60"/>
      <el-table-column prop="equipName" label="设备名称"/>
      <el-table-column prop="equipCode" label="设备编号"/>
      <el-table-column prop="equipCount" label="数量" width="70"/>
      <el-table-column prop="price" label="单价(元)"/>
      <el-table-column label="采购日期">
        <template #default="{row}">{{ formatDate(row.purchaseDate) }}</template>
      </el-table-column>
      <el-table-column label="上次维护">
        <template #default="{row}">{{ formatDate(row.lastMaintenanceDate) }}</template>
      </el-table-column>
      <el-table-column label="下次维护">
        <template #default="{row}">{{ formatDate(row.nextMaintenanceDate) }}</template>
      </el-table-column>
      <el-table-column prop="roomName" label="所属科室"/>
      <el-table-column label="设备状态" width="70">
        <template #default="{row}">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '正常' : '报废' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="维护状态" width="90">
        <template #default="{row}">
          <el-tag
              :type="getMaintenanceStatusType(row.maintenanceStatus)"
              :effect="row.maintenanceStatus === 1 ? 'dark' : 'light'">
            {{ getMaintenanceStatusText(row.maintenanceStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{row}">
          <el-button size="small" @click="handleEdit(row)">编辑</el-button>
          <el-button
              size="small"
              type="warning"
              @click="handleMaintenance(row)"
              :disabled="row.maintenanceStatus !== 1">
            确认维护
          </el-button>
          <el-button size="small" type="danger" @click="handleDel(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        :page-size="pagination.pageSize"
        :current-page="pagination.pageNum"
        :page-sizes="[5, 10, 20, 50]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
  </el-card>

  <!-- 新增/编辑弹窗 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="520px">
    <el-form :model="form" ref="formRef" label-width="90px" :rules="formRules">
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="设备名称" prop="equipName">
            <el-input v-model="form.equipName" placeholder="请输入设备名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备编号" prop="equipCode">
            <el-input v-model="form.equipCode" placeholder="请输入编号"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数量" prop="equipCount">
            <el-input-number v-model="form.equipCount" :min="1" style="width:100%"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="单价(元)" prop="price">
            <el-input-number v-model="form.price" :min="0" :precision="2" style="width:100%"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="采购日期" prop="purchaseDate">
            <el-date-picker
                v-model="form.purchaseDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择采购日期"
                style="width:100%"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属科室" prop="medicalRoomId">
            <el-select v-model="form.medicalRoomId" clearable placeholder="请选择科室" style="width:100%">
              <el-option v-for="item in roomListOpts" :key="item.id" :label="item.roomName" :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" style="width:100%">
              <el-option :value="1" label="正常"/>
              <el-option :value="0" label="报废"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible=false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  findEquipment,
  listEquipment,
  addEquipment,
  updateEquipment,
  delEquipment,
  confirmMaintenance
} from '../api/equipment.js'
import { roomList } from '../api/ward.js'

export default {
  name: 'EquipmentView',
  data() {
    return {
      queryParams: {
        equipName: '',
        roomName: '',
        status: ''
      },
      pagination: {pageNum: 1, pageSize: 10, total: 0},
      tableData: [],
      dialogVisible: false,
      dialogTitle: '',
      isAdd: true,
      form: {},
      allNameOpts: [],        // 设备名下拉
      roomListOpts: [],       // 科室下拉（独立接口）
      maintenanceCount: 0,    // 需要维护的设备数量
      formRules: {
        equipName: [{required: true, message: '请输入设备名称', trigger: 'blur'}],
        equipCode: [{required: true, message: '请输入设备编号', trigger: 'blur'}],
        equipCount: [{required: true, message: '请输入数量', trigger: 'blur'}],
        price: [{required: true, message: '请输入单价', trigger: 'blur'}],
        purchaseDate: [{required: true, message: '请选择采购日期', trigger: 'change'}],
        medicalRoomId: [{required: true, message: '请选择科室', trigger: 'change'}],
        status: [{required: true, message: '请选择状态', trigger: 'change'}]
      }
    }
  },
  mounted() {
    this.loadData()
    this.loadRoomList()      // 加载科室下拉
    this.loadAllSelectOptions()
  },
  methods: {
    /* -------------- 数据加载 -------------- */
    async loadData() {
      const hasCondition = this.queryParams.equipName || this.queryParams.roomName || this.queryParams.status !== ''
      const api = hasCondition ? listEquipment : findEquipment
      const params = {...this.queryParams, pageNum: this.pagination.pageNum, pageSize: this.pagination.pageSize}
      const {data: res} = await api(params)
      if (res.code === 200) {
        const list = res.obj?.list || []
        this.tableData = list
        this.pagination.total = res.obj?.total || 0

        // 计算需要维护的设备数量
        this.maintenanceCount = list.filter(item => item.maintenanceStatus === 1).length
      } else {
        ElMessage.error(res.msg || '获取数据失败')
      }
    },
    async loadAllSelectOptions() {
      const {data: res} = await findEquipment({pageNum: 1, pageSize: 10000})
      if (res.code === 200) {
        const list = res.obj?.list || []
        this.allNameOpts = [...new Set(list.map(i => i.equipName).filter(Boolean))].sort()
      }
    },
    /* 科室下拉独立接口 */
    async loadRoomList() {
      const {data: res} = await roomList()
      if (res.code === 200) {
        this.roomListOpts = res.obj || []
      }
    },
    /* -------------- 工具方法 -------------- */
    formatDate(d) {
      if (!d) return '-'
      return typeof d === 'string' ? d.split(' ')[0] : new Date(d).toLocaleDateString()
    },
    getMaintenanceStatusType(status) {
      const types = {
        1: 'danger',   // 需维护 - 红色
        2: 'success'   // 已维护 - 绿色
      }
      return types[status] || ''
    },
    getMaintenanceStatusText(status) {
      const texts = {
        1: '需维护',
        2: '已维护'
      }
      return texts[status] || '未知'
    },
    /* -------------- 查询/分页 -------------- */
    handleQuery() {
      this.pagination.pageNum = 1
      this.loadData()
    },
    handleReset() {
      this.queryParams = {
        equipName: '',
        roomName: '',
        status: ''
      }
      this.pagination.pageNum = 1
      this.loadData()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.loadData()
    },
    handleCurrentChange(val) {
      this.pagination.pageNum = val
      this.loadData()
    },
    /* -------------- 增删改 -------------- */
    handleAdd() {
      this.isAdd = true
      this.dialogTitle = '新增设备'
      this.form = {equipCount: 1, price: 0, status: 1}
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.isAdd = false
      this.dialogTitle = '编辑设备'
      this.form = {...row}
      this.dialogVisible = true
    },
    submitForm() {
      this.$refs.formRef.validate(async valid => {
        if (!valid) return

        // 处理日期格式
        const submitData = {...this.form}
        if (submitData.purchaseDate) {
          submitData.purchaseDate = submitData.purchaseDate + ' 00:00:00'
        }

        const api = this.isAdd ? addEquipment : updateEquipment
        const {data: res} = await api(submitData)
        if (res.code === 200) {
          ElMessage.success(this.isAdd ? '新增成功' : '修改成功')
          this.dialogVisible = false
          this.loadData()
          this.loadAllSelectOptions()
        } else {
          ElMessage.error(res.msg || '操作失败')
        }
      })
    },
    handleDel(row) {
      ElMessageBox.confirm('确认删除该设备？', '提示', {type: 'warning'})
          .then(async () => {
            const {data: res} = await delEquipment(row.id)
            if (res.code === 200) {
              ElMessage.success('删除成功')
              this.loadData()
              this.loadAllSelectOptions()
            } else {
              ElMessage.error(res.msg || '删除失败')
            }
          })
          .catch(() => {
          })
    },
    /* -------------- 维护操作 -------------- */
    async handleMaintenance(row) {
      try {
        await ElMessageBox.confirm(
            `确认设备 ${row.equipName} 已完成维护？`,
            '确认维护',
            { type: 'warning' }
        )

        // 调用维护确认API（使用您现有的/equip/confirm接口）
        const {data: res} = await confirmMaintenance(row.id)
        if (res.code === 200) {
          ElMessage.success('维护确认成功')
          this.loadData() // 重新加载数据
        } else {
          ElMessage.error(res.msg || '维护确认失败')
        }
      } catch (error) {
        // 用户取消操作
      }
    }
  }
}
</script>

<style scoped>
.search-form {
  margin-bottom: 12px;
}
</style>